/**
 * Created by Arnald on 2017/5/24.
 */
let userDao = require('../mysql/userDao.js');
let taskDao = require('../mysql/taskDao.js');
let signInDao = require('../mysql/signInDao.js');
let loginDao = require('../mysql/loginDao.js');
let advanceDao = require('../mysql/advanceDao.js');
let bluedSDK = require('../util/bluedSDK.js');
let util = require('../util/util.js');
let msg = require('../util/msg.js');
let rpc = require('../util/rpc.js');
let gameData = require('../util/gameData.js');
require('../util/prototype.js');

let login = module.exports;

login.ranking = function (userId, accessToken, bluedId, cb) {
    // if (accessToken) {
    //     bluedSDK.friends(accessToken, bluedId, function (res3) {
    //         if (res3.code != 200){
    //             return false;
    //         }
    //         let uidList = [];
    //         for (let i in res3.data) {
    //             uidList.push(res3.data[i].uid);
    //         }
    //         if (uidList.length <= 0) {
    //             return false;
    //         }
    //         login.friendRankList(uidList, function (rank) {
    //             login.giftList(userId, rank, cb);
    //         });
    //     });

    // } else {
        if (!gameData.d.config.touristLogin) {
            return false;
        }
        login.allRankList(userId, function (rank) {
            login.giftList(userId, rank, cb);
        });
    // }
};
login.giftList = function (userId, rank, cb) {
    let date = new Date().Format("yyyy-MM-dd");
    advanceDao.init().table('gift').pluck('userId')
        .wheres('sourceId', '=', userId).wheres('date', '=', date).get(function (err, res) {
        if (err !== null) {
            cb(rank);
            return false;
        } else if (res.length == 0) {
            cb(rank);
            return false;
        }
        let ids = [];
        for (let i in res) {
            ids.push(res[i].userId);
        }
        for (let i in rank) {
            if (ids.indexOf(rank[i].id) >= 0) {
                rank[i].gift = true;
            }
        }
        cb(rank);
    });
};
login.friendRankList = function (uidList, cb) {
    advanceDao.init().table('user').pluck('id', 'name', 'avatar', 'playVictory', 'playWins')
        .limit(15).orders('playWins', 'DESC').ranking(uidList, function (err, res) {
        if (err !== null) {
            cb(null);
        } else if (res.length == 0) {
            cb(null);
        } else {
            cb(res);
        }
    });
};
login.allRankList = function (userId, cb) {
    advanceDao.init().table('user').pluck('id', 'name', 'avatar', 'playVictory', 'playWins')
        .wheres('id', '!=', userId).limit(15).orders('playWins', 'DESC').get(function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            let rank = [];
            res.forEach(function (data) {
                data.gift = false;
                rank.push(data);
            });
            cb(rank);
        }
    });
};

login.package = function (userId, cb) {
    let time = Math.floor(Date.now() / 1000);
    advanceDao.init().table('package').wheres('userId', '=', userId).get(function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            for (let i in res) {
                res[i] = util.itemInfo(res[i], time);
            }
            cb(res);
        }
    });
};

login.daily = function (userId, cb) {
    let loginModel = new loginDao();
    loginModel.inToDay(userId, new Date().Format("yyyy-MM-dd"), function (err, res) {
        if (err || res) {
            login.task(userId, cb);
            return false;
        }
        loginModel.set('userId', userId);
        loginModel.set('date', new Date().Format("yyyy-MM-dd hh:mm:ss"));
        loginModel.save(function () {
            login.reTask(userId, cb);
        });
    });
};

login.reUser = function(userId){

};

login.task = function (userId, cb) {
    advanceDao.init().table('task').pluck('taskId', 'num').wheres('userId', '=', userId).get(function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            let data = {};
            for (let i in res) {
                data[res[i].taskId] = res[i].num;
            }
            cb(data);
        }
    });
};

login.reTask = function (userId, cb) {
    advanceDao.init().table('task').wheres('userId', '=', userId).delete(function () {
        let taskIds = [];
        let randTaskTables = {};
        for (let i in gameData.d.task) {
            if (!gameData.d.task[i].fixed) {
                continue;
            }
            taskIds.push(gameData.d.task[i].id);
        }
        let loss = gameData.d.config.dailyTaskAmount - taskIds.length;
        if (loss > 0) {
            for (let i in gameData.d.task) {
                if (gameData.d.task[i].fixed) {
                    continue;
                }
                randTaskTables[gameData.d.task[i].id] = gameData.d.task[i].rate;
            }
            while (true) {
                let key = util.roundTable(randTaskTables);
                taskIds.push(key);
                delete randTaskTables[key];
                if (gameData.d.config.dailyTaskAmount - taskIds.length <= 0) {
                    break;
                }
            }
        }
        let data = {};
        for (let i in taskIds) {
            data[taskIds[i]] = 0;
            let taskModel = new taskDao();
            taskModel.set('userId', userId);
            taskModel.set('taskId', taskIds[i]);
            taskModel.set('num', 0);
            taskModel.save(function (err, res) {
            });
        }
        cb(data);
    });
};

login.signIn = function (userId, cb) {
    let signInModel = new signInDao();
    signInModel.inId(userId, function (err, res) {
        if (!res) {
            signInModel.isInsert();
            signInModel.set('id', userId);
            signInModel.set('times', 0);
            signInModel.set('date', '2017-01-01');
            signInModel.save(function () {
                cb(true, 0);
            });
        } else {
            let date = new Date();
            let dateN = new Date(res.res.date);
            let ymd = date.Format("yyyy-MM-dd");
            let ymdN = dateN.Format('yyyy-MM-dd');
            if (ymd != ymdN) {
                if (parseInt(Math.abs(date - dateN) / 1000 / 60 / 60 / 24) > 1) {
                    res.res.times = 0;
                }
                cb(true, res.res.times);
            } else {
                //cb(false);
                return false;
            }
        }
    });
};

login.chip = function (userId, cb) {
    advanceDao.init().table('chip').wheres('userId', '=', userId).get(function (err, res) {
        if (err !== null) {
            return false;
        } else if (res.length == 0) {
            return false;
        } else {
            let data = {};
            for (let i in res) {
                data[res[i].chipId] = res[i].num;
            }
            cb(data);
        }
    });
};

login.run = function (cid, uuid, res) {
    msg.broadcast(uuid, 'enterKick', {'id': res.res.id});
    let loginData = {
        'id': res.res.id,
        'bluedId': res.res.bluedId,
        'name': res.res.name,
        'gold': res.res.gold,
        'score': res.res.score,
        'gem': res.res.gem,
        'card': res.res.card,
        'tradeGold': res.res.tradeGold,
        'avatar': res.res.avatar,
        'playTimes': res.res.playTimes,
        'playVictory': res.res.playVictory,
        'playWins': res.res.playWins,
        'gameId': res.res.gameId,
        'weixinId': res.res.weixinId,
        'serverTime': (new Date().getTime())
    };  
    console.log("login.run>>>>>");
    console.log(loginData);
    console.log(res.res);
    if (res.res.bluedId) {
        rpc.dc.send('getBlued', {'uid': res.res.bluedId}, function (data) {
            loginData.platform = data.platform;
            loginData.accessToken = data.accessToken;
            msg.send(cid, uuid, 'enterLogin', loginData);
            login.ranking(res.res.id, data.accessToken, res.res.bluedId, function (res2) {
                msg.send(cid, uuid, 'enterRanking', {'rank': res2});
            });
            login.other(cid, uuid, res);
        });
    }else if(res.res.weixinId){
        rpc.dc.send('getWeixin', {'uid': res.res.weixinId}, function (data) {
            loginData.platform = data.platform;
            loginData.accessToken = data.accessToken; 
            msg.send(cid, uuid, 'enterLogin', loginData);
            login.ranking(res.res.id, data.accessToken, res.res.weixinId, function (res2) {
                msg.send(cid, uuid, 'enterRanking', {'rank': res2});
            });
            login.other(cid, uuid, res);
        });
    } else {
        msg.send(cid, uuid, 'enterLogin', loginData);
        //msg.send(cid, uuid, 'enterRanking', {'rank': []});
        login.ranking(res.res.id, null, null, function (res2) {
            msg.send(cid, uuid, 'enterRanking', {'rank': res2});
        });
        login.other(cid, uuid, res);
    }
};

login.other = function (cid, uuid, res) {
    login.daily(res.res.id, function (res2) {
        msg.send(cid, uuid, 'enterTask', res2);
    });
    login.signIn(res.res.id, function (needSign, times) {
        msg.send(cid, uuid, 'enterSignIn', {'times': times});
    });
    //login.package(res.res.id, function (res3) {
    //    msg.send(cid, uuid, 'enterPackage', res3);
    //});
    login.chip(res.res.id, function (res4) {
        msg.send(cid, uuid, 'enterChip', res4);
    });
};

login.enter = function (cid, uuid, data) {
    let userModel = new userDao();
    userModel.inToken(data.token, function (err, res) {
        if (res == null) {
            msg.send(cid, uuid, 'error', {'api': 'enterToken', 'code': 10014});
            return false;
        }
        login.run(cid, uuid, res);
    });
};